<template>
  <div>
    <el-form ref="pram" :model="pram" :rules="rules" label-width="100px" @submit.native.prevent>
      <el-form-item label="工作地点：" prop="address">
        <el-tooltip content="请点击查找位置选择位置">
          <el-input v-model="pram.address" placeholder="请查找位置" class="dialogWidth" readOnly>
            <el-button slot="append" @click="onSearch">查找位置</el-button>
          </el-input>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="零活名称" prop="name">
        <el-input v-model="pram.name" maxlength="255" placeholder="零活名称" />
      </el-form-item>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="计价方式" prop="valuation">
            <el-select v-model="pram.valuation" placeholder="计价方式" clearable style="width: 100%">
              <el-option
                v-for="(item,index) in valuationList"
                :key="index"
                :label="item"
                :value="index+1"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="零活类型" prop="type">
            <el-cascader v-model="pram.type" :disabled="isCreate ===1 && pram.type ===0" :options="parentOptions" :props="categoryProps" style="width:100%" />
            <!-- allTreeList or parentOptions-->
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="开工日期" prop="start_time">
            <el-date-picker v-model="pram.start_time" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="选择开工日期" style="width:100%;"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预估工期：" prop="duration">
            <el-input v-model.number="pram.duration" type="number" :placeholder="([1,2].indexOf(pram.valuation) !== -1) ? (pram.valuation === 1 ? '预估工期，单位：天' : '预估工期，单位：小时') : '预估工期'"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="用工人数：" prop="population">
            <el-input v-model.number="pram.population" type="number" placeholder="用工人数，单位：个"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单价：" prop="price">
            <el-input v-model.number="pram.price" type="number" placeholder="单价，单位：元"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="工作描述：" prop="describe">
        <el-input v-model="pram.describe" type="textarea" :rows="3" placeholder="工作描述"></el-input>
      </el-form-item>
      <el-form-item :label="'图片('+pram.attachment.length +'/4)'" prop="attachment">
        <div class="acea-row" v-if="pram.attachment">
          <div
            v-for="(item,index) in pram.attachment"
            :key="index"
            class="pictrue mb10"
            draggable="true"
            @dragstart="handleDragStart($event, item)"
            @dragover.prevent="handleDragOver($event, item)"
            @dragenter="handleDragEnter($event, item)"
            @dragend="handleDragEnd($event, item)"
          >
            <el-image
              class="photo-el-image"
              :src="item"
              :preview-src-list="pram.attachment"
            />
            <i v-if="!isDisabled" class="el-icon-error btndel" @click="handleRemove(index)"/>
          </div>
          <!--            <div v-if="pram.swiperImage.length<6 && !isDisabled" class="upLoadPicBox" @click="modalPicTap('2')">-->
          <div v-if="pram.attachment.length<4 && !isDisabled" class="upLoadPicBox">
            <el-tooltip
              class="item"
              effect="dark"
              content="上传图片"
              placement="top-start"
            >
              <el-upload
                class="upload-demo"
                action
                accept="image/gif,image/jpeg,image/png"
                :before-upload="onBeforeUpload"
                :http-request="handleUploadFormSwiper"
                :headers="myHeaders"
                :show-file-list="false"
              >
                <el-button
                  icon="el-icon-plus"
                  class="mr15 definedArea"
                  style="width:120px;height:120px;"
                ></el-button>
              </el-upload>
            </el-tooltip>
          </div>
        </div>
        <span style="color: #ccc">（工作环境及操作规范）</span>
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="pram.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSubmit('pram')" v-hasPermi="['admin:work:insert']">{{ isCreate===0?'确定':'更新' }}</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="modalMap" title='上传经纬度' :visible.sync="modalMap" append-to-body class="mapBox" width="500px">
      <iframe
        id="mapPage" width="100%" height="100%" frameborder=0
        v-bind:src="keyUrl"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script>
import * as roleApi from '@/api/role.js'
import * as workApi from '@/api/workApi.js'
import {getToken} from "@/utils/auth";
import {Debounce} from '@/utils/validate'
import * as selfUtil from "@/utils/ZBKJIutil";
import Templates from "../appSetting/wxAccount/wxTemplate/index";
import {fileImageApi} from "@/api/systemSetting";
export default {
  // name: "edit"
  components: { Templates},
  props: {
    isCreate: {
      type: Number,
      required: true
    },
    editData: {
      type: Object,
      default: () => {
        return { rules: [] }
      }
    },
    allTreeList: {
      type: Array
    },
    allValuationList: {
      type: Array
    },
  },
  data() {
    const validatePrice = (rule, value, callback) => {
      let match = /(^[0-9]\d{0,3}$)|(^[0-9]\d{0,3}(\.\d{1,2}?)$)/
      if (!value) {
        return callback(new Error('请填写单价金额'));
      } else if (!match.test(value)) {
        ///^[1-0]\d{0,3}(\.\d{1,2}?)$/.test(str)||
        callback(new Error('单价金额最多不超过1万，小数点后面最多两位!'));
      } else {
        callback();
      }
    };
    const validatePopulation = (rule, value, callback) => {
      let match = /(^[1-9]\d*$)/
      if (!value) {
        return callback(new Error('请填写用工人数'));
      } else if (!match.test(value)) {
        callback(new Error('用工人数必须是正整数!'));
      } else {
        callback();
      }
    };

    const validateDuration = (rule, value, callback) => {
      let match = /(^[1-9]\d*$)/
      if (!value) {
        return callback(new Error('请填写预估工期'));
      } else if (!match.test(value)) {
        callback(new Error('预估工期必须是正整数!'));
      } else {
        callback();
      }
    };
    return {
      constants:this.$constants,
      isDisabled: this.$route.params.isDisabled==='1'?true:false,
      modalMap: false,
      keyUrl: '',
      pram: {
        address:null,
        latitude: null,
        longitude:null,
        name:null,
        valuation:null,
        type:null,
        start_time:null,
        duration: null,
        population:null,
        price: null,
        describe: null,
        attachment:[],
        status: 1,
        id: null,
      },
      roleList: {},
      rules: {
        address: [{ required: true, message: '请选择工作地点', trigger: ['blur', 'change'] }],
        latitude: [{ required: true, message: '请选择工作地点', trigger: 'blur' }],
        longitude: [{ required: true, message: '请选择工作地点', trigger: 'blur' }],
        name: [{ required: true, message: '请填零活名称', trigger: ['blur', 'change'] }],
        valuation: [{ required: true, message: '请选计价方式', trigger: ['blur', 'change'] }],
        type: [{ required: true, message: '请选零活类型', trigger: ['blur', 'change'] }],
        start_time: [{ required: true, message: '请选开工日期', trigger: ['blur', 'change'] }],
        duration: [{ required: true, validator: validateDuration, trigger: ['blur', 'change'] }],
        population: [{ required: true, validator: validatePopulation, trigger: ['blur', 'change'] }],
        price: [{ required: true, validator: validatePrice, trigger: ['blur', 'change'] }],
        describe: [{ required: true, message: '请填描述', trigger: ['blur'] }],
        attachment: [{ required: true, message: '请上传图片', trigger: ['blur', 'change'] }],
      },
      valuationList:[],

      categoryProps: {
        value: 'id',
        label: 'name',
        children: 'child',
        expandTrigger: 'hover',
        checkStrictly: true,
        emitPath: false
      },
      parentOptions: [],

      myHeaders: { "X-Token": getToken() },
      localFile: null,
      dialogImageUrl: null,
    }
  },
  mounted() {
    window.addEventListener('message', function (event) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module === 'locationPicker') { // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        window.parent.selectAdderss(loc);
      }
    }, false);
    window.selectAdderss = this.selectAdderss;

    this.initEditData()
    this.getKey();
  },
  methods: {
    close() {
      this.$emit('hideEditDialog')
    },

    //查找位置
    onSearch () {
      this.modalMap = true;
    },
    // 选择经纬度
    selectAdderss (data) {
      this.pram.address = data.poiaddress;
      this.pram.longitude = data.latlng.lng;
      this.pram.latitude = data.latlng.lat;
      this.modalMap = false;
    },
    // key值
    getKey () {
      let tengxun_map_key = "ZILBZ-FEDCL-6M3PO-M7GUW-PXP5T-ABFB4";
      this.keyUrl = `https://apis.map.qq.com/tools/locpicker?type=1&key=${tengxun_map_key}&referer=myapp`;
    },

    //营业时间
    onchangeTime(e){
      this.pram.start_time = e;
    },

    initEditData() {
      this.valuationList = this.allValuationList
      this.parentOptions = [...this.allTreeList]
      this.addTreeListLabelForCasCard(this.parentOptions, 'child')

      if (this.isCreate !== 1) return //编辑
      const { address, latitude, longitude, name, valuation, type, start_time_text, duration, population, price, describe, attachment, status, id } = this.editData //通过list中slot-scope=“scope“，scope.$index就是该行的下标，scope.row就是该行的数据所有消息对象，有了这两个参数就可以实现编辑、删除功能（this.editData就是scope.row传入的对象参数）
      this.pram.address = address
      this.pram.latitude = latitude
      this.pram.longitude = longitude
      this.pram.name = name
      this.pram.valuation = valuation
      this.pram.type = type
      this.pram.start_time = start_time_text
      this.pram.duration = duration
      this.pram.population = population
      this.pram.price = price
      this.pram.describe = describe
      this.pram.attachment = attachment
      this.pram.status = status
      this.pram.id = id
    },
    //处理哪一级别禁用
    addTreeListLabelForCasCard(arr, child) {
      arr.forEach((o,i) => {
        if (o.child && o.child.length) {
          o.disabled = true
          /*o.child.forEach((j) => {
            j.disabled = true
          })*/
        }
      })

    },

    handlerSubmit:Debounce(function(form) {
      this.$refs[form].validate(valid => {
        if (!valid) return
        if (this.isCreate === 0) {
          this.handlerSave()
        } else {
          this.handlerEdit()
        }
      })
    }),
    handlerSave() {
      //console.log(this.pram);return;
      workApi.doAdd(this.pram).then(data => {
        this.$message.success('创建成功')
        this.$emit('hideEditDialog')
      })
    },
    handlerEdit() {
      //this.pram.roles = this.pram.roles.join(',')
      //console.log(this.pram);return;
      workApi.doAdd(this.pram).then(data => {
        this.$message.success('更新成功')
        this.$emit('hideEditDialog')
      })
    },

    //图片上传有关
    onBeforeUpload(file) {
      const isIMAGE = file.type === 'image/jpg'||'image/gif'||'image/png';
      const isLt1M = file.size / 1024 / 1024 < 10;

      if (!isIMAGE) {
        this.$message.error('上传文件只能是jpg、png或gif格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isIMAGE && isLt1M;
    },
    //轮播图上传
    handleRemove (i) {
      this.pram.attachment.splice(i, 1)
    },
    handleUploadFormSwiper(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      fileImageApi(formData).then((res) => {
        //图片上传接口 后期调用
        this.pram.attachment.push(res)

        loading.close();
        this.$message.success("上传成功");
      })
        .catch((res) => {
          console.log(res)
          loading.close();
        });
    },
    // 移动
    handleDragStart (e, item) {
      if(!this.isDisabled) this.dragging = item;
    },
    handleDragEnd (e, item) {
      if(!this.isDisabled) this.dragging = null
    },
    handleDragOver (e) {
      if(!this.isDisabled) e.dataTransfer.dropEffect = 'move'
    },
    handleDragEnter (e, item) {
      if(!this.isDisabled){
        e.dataTransfer.effectAllowed = 'move'
        if (item === this.dragging) {
          return
        }
        const newItems = [...this.pram.attachment]
        const src = newItems.indexOf(this.dragging)
        const dst = newItems.indexOf(item)
        newItems.splice(dst, 0, ...newItems.splice(src, 1))
        this.pram.attachment = newItems;
      }
    },
  }
}
</script>

<style lang="scss">
  .el-input-group__append, .el-input-group__prepend{
    background-color:#1890ff!important;
    color: #fff!important;
    border-color:#1890ff!important;
    border-radius: 0 4px 4px 0;
  }
  .cascaderW{
    width: 350px;
  }
  .mapBox .el-dialog__body{
    height: 640px !important;
  }

  .imgDel{
    position: absolute;
    z-index: 4;
    top: 1px;
    border: 0;
    width: 15px!important;
    height: 15px!important;
    text-align: center;
    //right: -1px;
    left:64px;
    padding: 0px!important;
    line-height: 10px!important;
    border-radius: 0!important;
    font-weight:bold;
  }
  .img-box{
    position:absolute;
    z-index: 3;
    top:0;
    width: 80px;
    height: 80px;
    border:0;
  }
  .pictrue{
    width: 120px;
    height: 120px;
    border: 1px dotted rgba(0,0,0,0.1);
    margin-right: 10px;
    position: relative;
    cursor: pointer;
    .photo-el-image{
      width: 100%;
      height: 100%;
    }
    img{
      width: 100%;
      height: 100%;
    }
    video{
      width: 100%;
      height: 100%;
    }
  }
  .btndel{
    position: absolute;
    z-index: 1;
    width :20px !important;
    height: 20px !important;
    font-size:20px;
    left: 100px;
    top: -2px;
  }
</style>
